package club.kynb.mall.application.flow.order;

import club.kynb.mall.application.assembler.MallCommonAssembler;
import club.kynb.mall.application.context.OrderPreviewContext;
import club.kynb.mall.application.model.model.dto.PreviewOrderDTO;
import club.kynb.mall.application.model.model.dto.PreviewOrderDetailDTO;
import club.kynb.mall.application.model.model.dto.PreviewOrderSpuDTO;
import club.kynb.mall.application.model.model.vo.OrderPreviewResultVO;
import club.kynb.mall.order.model.dto.ShoppingCartDTO;
import club.kynb.mall.product.dto.ProductSpuDetailDTO;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.pizza.id.api.IdGenerator;
import org.pizza.pattern.filter.Filter;
import org.pizza.pattern.filter.FilterInvoker;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author kynb_club@163.com
 * @since 2021/7/5 9:02 下午
 */
@Slf4j
@Component
@AllArgsConstructor
public class BuildOrderPreviewResultFilter implements Filter<OrderPreviewContext> {
    private final IdGenerator idGenerator;

    @Override
    public void doFilter(OrderPreviewContext orderPreviewContext, FilterInvoker<OrderPreviewContext> filterInvoker) {
        log.info("构建预览订单结果过滤器 start");
        final OrderPreviewResultVO orderPreviewResultVO = orderPreviewContext.getOrderPreviewResultVO();
        final PreviewOrderDTO previewOrderDTO = orderPreviewResultVO.getPreviewOrderDTO();
        //购物车商品转换预览订单详情
        final List<ShoppingCartDTO> checkedList = orderPreviewContext.getCheckedList();
        final List<ProductSpuDetailDTO> filteredList = orderPreviewContext.getFilteredSpuList();
        final List<PreviewOrderSpuDTO> itemList = MallCommonAssembler.assembleOrderSpuList(checkedList, filteredList);
        final List<PreviewOrderDetailDTO> detailList = itemList.stream()
                .map(previewOrderSpuDTO -> new PreviewOrderDetailDTO().setPreviewOrderSpuDTO(previewOrderSpuDTO))
                .collect(Collectors.toList());
        previewOrderDTO.setOrderDetailList(detailList);
        //配送时间设置
        final DateTime tomorrow = DateUtil.offsetDay(new Date(), 1);
        final String format = DateUtil.format(tomorrow, DatePattern.NORM_DATE_PATTERN);
        previewOrderDTO.setDeliveryTime(format + " 12:00:00前");
        //生成内部订单编号
        final long innerOrderNo = idGenerator.nextId(OrderPreviewResultVO.class);
        previewOrderDTO.setInnerOrderNo(String.valueOf(innerOrderNo));
        log.info("构建预览订单结果过滤器 end");
        filterInvoker.invoke(orderPreviewContext);
    }
}
